import path from 'path';
import fs from 'fs';

/**
 * 读取目录中的文件
 * @param {string} dirPath 目录路径
 * @param {boolean} recursive true: 递归读取; false: 只读取本层;
 * @param {boolean} file true: 读取目录中的文件; false: 不读取目录中的文件;
 * @param {boolean} directory true: 读取目录中的目录; false: 不读取目录中的目录;
 * @returns 目录中的文件/目录列表
 */
export default function readdirSync(dirPath, recursive = true, file = true, directory = false, files = []) {
    if (!fs.existsSync(dirPath)) { return files; }
    if (!fs.statSync(dirPath).isDirectory()) { return files; }

    fs.readdirSync(dirPath).forEach(filename => {
        const filePath = path.join(dirPath, filename);
        const stats = fs.statSync(filePath);
        if (stats.isFile()) {
            if (file === true) { files.push(filePath); }
        } else if (stats.isDirectory()) {
            if (directory === true) { files.push(filePath); }
            if (recursive === true) { readdirSync(filePath, recursive, file, directory, files); }
        }
    });

    return files;
}
